import i18n from '@/lang';

import { getSystemConfig } from '@/api/system';

import store from '@/store';

import { LOCAL_KEY } from '@/constant/dict';

export function createGuard(router) {
    router.beforeEach(async (to, from, next) => {
        // 1. wizard 检查
        let isLoginPage = to.path === '/login';
        let isNeedWizard = true;
        // 如果需要则通过后台请求判断是否已经做过wizard。
        let isWizard = false;
        if (!isLoginPage && isNeedWizard) {
            let isLoadConfig = store.state.config.isLoadConfig;
            if(!isLoadConfig){
                try{
                    //let {isWizard} = await getSystemConfig();
                    isWizard = false;
                    store.commit('config/SET_WIZARD', isWizard);
                    store.commit('config/SET_LOAD_CONFIG', true);
                } catch (e) {
                    console.log(e);
                }
            }
            isWizard = store.state.config.isWizard;
        }

        console.log('to:', to.path, 'from:', from.path,'isNeedWizard:', isNeedWizard, 'isWizard:', isWizard);
        
        // 2. Login 拦截
        if(isNeedWizard && isWizard){
            // 需要进入 wizard页面
            console.log('wizard page =',to.path.startsWith('/wizard'))
            if (!to.path.startsWith('/wizard')) {
                next('/wizard');
            }else{
                next();
            }
        }else {
            // 登录鉴权拦截检查
            console.log('login intercept',localStorage.getItem(LOCAL_KEY.IS_AUTH_TOKEN));
            if (whiteListTest(to.path) && !to.path.startsWith('/wizard')) {
                // 没有登录并且要去的页面不是登录页面，在强制跳转到登录
                if (isLoginPage) {
                    if (localStorage.getItem(LOCAL_KEY.IS_AUTH_TOKEN)) {
                        next('/home');
                    } else {
                        next();
                    }
                } else if (!localStorage.getItem(LOCAL_KEY.IS_AUTH_TOKEN)) {
                    next('/login');
                } else {
                    next();
                }
            } else {
                next('/home');
            }
        }
    });
}

// 根据白名单控制路由
const whiteListTest = (path) => {
    // 获取当前项目名
    const currentProject = process.env.VUE_APP_PROJECT_NAME;
    return true;
};

